<template>
  <q-page class="">
    <div class="container">
      <div class="row q-col-gutter-md">
        <div class="col-12">
          <div class="row q-col-gutter-md">
            <div class="col-12 text-center text-h5">
              Box统计工具
            </div>
            <div class="col-12">
              <q-input dense label="名称" v-model="name" :readonly="!!account.nickname"/>
            </div>
          </div>
        </div>
        <div class="col-12">
          <div class="row q-col-gutter-md" v-if="name && name.length > 0 && !loading && fullList">
            <div class="col-xs-6 col-sm-6 col-md-3">
              <q-btn class="full-width" color="primary" label="上传保存" @click="onUploadEvent"
                     :disable="!account.username"/>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-3">
              <q-btn class="full-width" color="primary" label="下载同步" @click="onDownloadEvent"
                     :disable="!account.username"/>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-3">
              <q-btn class="full-width" color="orange" label="导出数据" @click="exportData"/>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-3">
              <q-btn class="full-width" color="purple" label="导入数据" @click="importData"/>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-btn class="full-width" color="secondary" label="添加角色" @click="addCharacterDialogDisplay = true;"/>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-btn class="full-width" color="red" label="清空box" @click="doClearBox" no-caps/>
            </div>
            <div class="col-12">
              <character-list v-model="showBox" @click="onBoxItemClickEvent"/>
            </div>
          </div>
          <div class="row q-col-gutter-md" v-else-if="!name || name.length <= 0">
            <div class="col-12 text-center text-body1">
              请先输入您的名称！
            </div>
          </div>
          <div class="row q-col-gutter-md" v-else-if="!loading && !fullList">
            <div class="col-12 text-center text-body1">
              载入失败，请检查你的网络连接是否良好！
            </div>
          </div>
          <div class="row q-col-gutter-md" v-else>
            <div class="col-12 text-center text-body1">
              载入中，请稍候……
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--添加角色对话框-->
    <add-character v-model="addCharacterDialogDisplay" :list="restList" @click="onAddCharacterEvent"/>
    <!--编辑角色对话框-->
    <edit-character v-model="editCharacterDialogDisplay"
                    :data="characterData"
                    :info="characterInfo"
                    @update="onUpdateCharacterDataEvent"
                    @remove="onRemoveCharacterEvent"/>
  </q-page>
</template>

<script>
import CharacterList from "components/CharacterList";
import AddCharacter from "components/AddCharacter";
import EditCharacter from "components/EditCharacter";
import BigFun from "src/lib/api/bigfun";
import Character from 'src/lib/api/characterInfo';
import {copyToClipboard} from "quasar";
import Box from "src/lib/api/box";

export default {
  name: 'PageBox',
  components: {EditCharacter, CharacterList, AddCharacter},
  data: function () {
    return {
      fullList: null,
      addCharacterDialogDisplay: false,
      editCharacterDialogDisplay: false,
      loading: false,
      loadingCharacterInfo: false,
      characterInfo: null,
      characterData: null
    };
  },
  watch: {},
  computed: {
    account: {
      get() {
        if (this.$store.state.account.nickname) this.$store.commit('box/updateName', this.$store.state.account.nickname);
        return this.$store.state.account;
      }
    },
    name: {
      get() {
        return this.$store.state.account.nickname || this.$store.state.box.name;
      },
      set(v) {
        this.$store.commit('box/updateName', v);
      }
    },
    box: {
      get() {
        return this.$store.getters['box/box'];
      },
      set(v) {
        this.$store.commit('box/update', v);
      }
    },
    showBox: {
      get() {
        let box = this.box;
        let list = [];
        for (const i of box) {
          const c = this.getCharacterById(i.id);
          if (this.fullList && c) list.push({
            star: i.star,
            rank: i.rank,
            equipment: i.equipment,
            weapon: i.weapon,
            ...c
          });
        }
        return list;
      }
    },
    restList: {
      get() {
        if (!this.fullList) return [];
        let box = this.box;
        let list = [];
        for (const i of this.fullList) {
          let has = false;
          for (const j of box) {
            if (i.id === j.id) {
              has = true;
              break;
            }
          }
          if (!has) list.push(i);
        }
        return list;
      }
    }
  },
  methods: {
    async onUploadEvent() {
      this.$q.dialog({
        title: '确认上传',
        message: '确认要上传角色信息吗？您之前保存在服务器的角色信息都将被覆盖！',
        cancel: true,
        persistent: true
      }).onOk(async () => {
          this.$q.loading.show({
            message: '正在上传，请稍候……'
          });
          try {
            await Box.upload();
          } catch (e) {
            console.log(e);
          }
          this.$q.loading.hide();
        }
      )
    },
    async onDownloadEvent() {
      this.$q.dialog({
        title: '确认下载',
        message: '确认要下载角色信息吗？您保存在本地的角色信息都将被覆盖！',
        cancel: true,
        persistent: true
      }).onOk(async () => {
          this.$q.loading.show({
            message: '正在下载，请稍候……'
          });
          try {
            let box = await Box.download();
            if (box) {
              this.$store.commit('box/forceImportState', {
                name: this.$store.state.box.name,
                box
              });
              await this.$router.go(0);
            }
          } catch (e) {
            console.log(e);
          }
          this.$q.loading.hide();
        }
      )
    },
    async onAddCharacterEvent(id) {
      this.$q.loading.show();
      this.$store.commit('box/add', {
        id: id,
        star: (await BigFun.getCharacterInfo(id))[0].level
      });
      this.addCharacterDialogDisplay = false;
      this.$q.loading.hide();
    },
    onUpdateCharacterDataEvent(data) {
      if (data) this.$store.commit('box/update', data);
    },
    onRemoveCharacterEvent(id) {
      this.$store.commit('box/remove', id);
      this.editCharacterDialogDisplay = false;
    },
    getCharacterById(id) {
      for (const i of this.fullList) {
        if (id === i.id) return i;
      }
      return null;
    },
    onBoxItemClickEvent(id) {
      this.characterInfo = null;
      this.characterData = this.getBoxCharacterData(id);
      this.onLoadCharacterInfo(id);
      this.editCharacterDialogDisplay = true;
    },
    async onLoadCharacterInfo(id) {
      this.loadingCharacterInfo = true;
      const i = await BigFun.getCharacterInfo(id);
      if (i.length > 0) this.characterInfo = i[0];
      this.characterInfo.name = this.getCharacterById(id).name;
      this.loadingCharacterInfo = false;
    },
    getBoxCharacterData(id) {
      const box = this.box;
      for (const i of box) {
        if (i.id === id) return JSON.parse(JSON.stringify(i));
      }
      return null;
    },
    exportData() {
      try {
        const base64 = btoa(encodeURI(JSON.stringify(this.$store.state.box)));
        copyToClipboard(base64).then(() => {
            this.$q.notify({
              message: '成功',
              caption: '已成功将角色信息复制到剪切板。',
              icon: 'check'
            });
          }
        ).catch(() => {
          this.$q.notify({
            message: '失败',
            caption: '复制角色信息到剪切板失败。',
            icon: 'clear'
          });
          this.$q.dialog({
            title: '手动复制',
            message: '请手动复制下方框内的文本：',
            prompt: {
              model: base64,
              type: 'text'
            }
          });
        })
      } catch (e) {
        this.$q.notify({
          message: '失败',
          caption: '生成角色信息编码失败。',
          icon: 'clear'
        });
      }
    },
    importData() {
      this.$q.dialog({
        title: '导入角色数据',
        message: '请将使用本工具导出的文本复制到下方的文本框内：',
        prompt: {
          model: '',
          type: 'text' // optional
        },
        cancel: true,
        persistent: true
      }).onOk(data => {
        this.$q.dialog({
          title: '确认导入',
          message: '确认要导入角色信息吗？您当前本地保存的角色信息都将被覆盖！',
          cancel: true,
          persistent: true
        }).onOk(() => {
          try {
            const box = JSON.parse(decodeURI(atob(data)));
            box.name = this.name;
            this.$store.commit('box/forceImportState', box);
            this.$q.notify({
              message: '成功',
              caption: '已成功导入角色信息。',
              icon: 'check'
            });
            this.$router.go(0);
          } catch (e) {
            this.$q.notify({
              message: '失败',
              caption: '导入角色信息失败。',
              icon: 'clear'
            });
          }
        })
      })
    },
    doClearBox() {
      this.$q.dialog({
        title: '确认清空',
        message: '确认要清空角色信息吗？您当前本地保存的角色信息都将丢失！',
        cancel: true,
        persistent: true
      }).onOk(() => {
        try {
          this.$store.commit('box/forceImportState', {
            name: this.name,
            box: []
          });
          this.$q.notify({
            message: '成功',
            caption: '已成功清空角色信息。',
            icon: 'check'
          });
          this.$router.go(0);
        } catch (e) {
          this.$q.notify({
            message: '失败',
            caption: '清空角色信息失败。',
            icon: 'clear'
          });
        }
      })
    }
  },
  async mounted() {
    this.loading = true;
    this.fullList = await Character.getCharacterList();
    this.loading = false;
  }
}
</script>

<style>

</style>
